<template>
  <div class="table-list-main">
    <el-tabs v-model="tabActiveName" class="tabs" @tab-change="tabChange">
      <el-tab-pane v-for="(item,index) in tabList" :key="index" :label="item.label" :name="item.name">
      </el-tab-pane>
    </el-tabs>
    <div class="table-search">
      <el-form :inline="true" :model="searchForm" label-width="120px">
        <el-form-item label="发送状态：">
          <el-select 
            v-model="searchForm.sendStatus" 
            @change="sendStatusChange"
            clearable
            placeholder="请选择发送状态">
            <el-option 
              v-for="item in sendStatus" 
              :key="item.code" 
              :label="item.label" 
              :value="item.code" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="发送方式：">
          <el-select v-model="searchForm.sendMethod" clearable placeholder="请选择发送方式">
            <el-option 
              v-for="item in sendMethod" 
              :key="item.code" 
              :label="item.label" 
              :value="item.code" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="群发通知时间" v-if="tabActiveName != 1">
          <el-date-picker 
            v-model="searchForm.date" 
            :disabled-date="(time: any) => time.getTime() > Date.now()"
            type="daterange" 
            start-placeholder="开始时间" 
            end-placeholder="结束时间" 
            format="YYYY-MM-DD HH:mm:ss" 
            value-format="YYYY-MM-DD HH:mm:ss" 
            @change="onChangeTime" />
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="onSearch">
          查找
        </el-button>
        <el-button @click="onReset">清空</el-button>
        <!-- <el-button 
          v-if="tabActiveName != 1" 
          type="primary" 
          @click="handlerSend">
          {{ tabActiveName == 3 ? '批量发送' : '重新发送'}}
        </el-button> -->
        <el-popover
          v-if="tabActiveName != 1" 
          placement="top-start"
          :width="190"
          trigger="hover"
        >
          <el-button size="small" type="primary" @click="handlerSend('2')">全量发送</el-button>
          <el-button size="small" type="primary" @click="handlerSend('1')">批量发送</el-button
          >
          <template #reference>
            <el-button type="primary">{{ tabActiveName == 3 ? '批量发送' : '重新发送'}}</el-button>
          </template>
        </el-popover>
      </div>
    </div>
    <el-table 
      :data="state.list" 
      style="width: 100%"
      @selection-change="handlerSelectionChange">
      <el-table-column v-if="tabActiveName != 1" type="selection"></el-table-column>
      <el-table-column prop="Id" label="编号" />
      <el-table-column v-if="tabActiveName == 3" prop="name" label="群发类型">
        <template #default="scope">
          {{ getListName(massTypeList, scope.row.MassType) }}
        </template>
      </el-table-column>
      <el-table-column prop="Title" label="群发标题" />
      <el-table-column prop="Describe" label="消息描述">
        <template #default="scope">
          <el-popover
            placement="top-start"
            :width="200"
            trigger="hover"
            :content="scope.row.Describe"
          >
            <template #reference>
              <div class="desc zw-text-ellipsis-2">{{ scope.row.Describe }}</div>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="NoticeTime" label="群发通知时间" />
      <el-table-column prop="SendStatus" label="发送状态">
        <template #default="scope">
            <div>
              {{ getListName(setStatusList, scope.row.SendStatus) }}
            </div>
          </template>
      </el-table-column>
      <el-table-column prop="MassType" label="执行进度">
        <template #default="scope">
          <div>
            <span> {{ scope.row.Completed }} / {{ scope.row.Count }}</span>
            <el-tooltip
              v-if="scope.row.HasException"
              class="box-item"
              effect="dark"
              placement="top-start"
            >
              <template #content> 
                {{ scope.row.ExceptionMsg || '-' }}
              </template>
              异常
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="SendTime" label="发送时间" />
      <el-table-column prop="options" label="操作" width="180px">
        <template #default="scope">
          <el-button v-if="scope.row.SendStatus == 3" size="small" @click="handlerSendItem(scope.row)">发送</el-button>
          <el-button size="small" @click="handlerPrivateLetter(scope.row)">私信清单</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination 
      layout="total,  prev, pager, next,sizes, jumper"
      :current-page="searchForm.page"
      :page-size="searchForm.page_size"
      :page-sizes="[15, 30, 50, 100]"
      :total="searchForm.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />

      <PrivateLetter v-model="isPrivateLetter" :id="privateLetterInfo.Id" :tabActiveType="tabActiveName" />
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import PrivateLetter from './PrivateLetter.vue'
import { getMassDispatchList, massDispatchSend } from '@renderer/ajax/api/groupMonitor'
import { getDate } from '@renderer/utils/utils'
import { ElMessage } from 'element-plus'

const tabActiveName = ref<any>('1')
const tabList = reactive<any>([
  {
    label: '今日群发事件',
    name: '1'
  },
  {
    label: '历史群发事件',
    name: '2'
  },
  {
    label: '第三方群发事件',
    name: '3'
  }
])

const sendStatus = reactive<any>([
  { label: '全部', code: '0' },
  {
    label: '已发送',
    code: '1'
  },
  {
    label: '发送中',
    code: '2'
  },
  {
    label: '未发送',
    code: '3'
  },
  { 
    label: '发送失败', 
    code: '4'
 }
])

const sendMethod = reactive<any>([
  {
    label: '自动群发',
    code: '1'
  },
  {
    label: '自动私信',
    code: '2'
  }
])

const setStatusList = [
  { label: '全部', code: '0' },
  { label: '已发送', code: '1' },
  { label: '发送中', code: '2' },
  { label: '未发送', code: '3' },
  { label: '发送失败', code: '4' },
]

const massTypeList = [
  { label: '客户', code: '1' },
  { label: '客户群', code: '2' },
  { label: '营销待办', code: '3' },
  { label: '客户sop', code: '4' },
  { label: '客户群sop', code: '5' },
  { label: '标签拉群', code: '6' }
]

const state = reactive({
  list: [],
  total: 0,
  SourceType: '',
  SendStatus: 0,
  page: 1,
  page_size: 15
})

const selectList = ref<any>([])

const searchForm = reactive({
  sendStatus: '0',
  date: [getDate('dayStartOf'),getDate('dayEndOf')],
  page: 1,
  page_size: 15,
  total: 0,
})

const isPrivateLetter = ref<boolean>(false)

const privateLetterInfo = reactive({
  Id: ''
})

const tabChange = (val) => {
  console.log(val)
  // isPrivateLetter.value = true
  getData()
}

const sendStatusChange = (val: any) => {
  console.log(val,'1')
  getData()
}

const onChangeTime = (v: any) => {
  v ? (searchForm.date[1] = `${v[1].split(' ')[0]} 23:59:59`) : (searchForm.date = [])
  console.log('时间筛选', searchForm.date)
  getData()
}


const handleSizeChange = (val: number) => {
  searchForm.page_size = val
  getData()
}

const handleCurrentChange = (val: number) => {
  searchForm.page = val
  getData()
}

const handlerSelectionChange = (val: any) => {
  console.log(val)
  selectList.value = val || []
}

const handlerSend = async (type?: any) => {
  console.log('xxx')
  let Ids = []
  if(type == '1') {
    if(!selectList.value.length) {
      ElMessage.warning('请选择需要重新发送的数据')
      return
    }
    Ids = selectList.value.map(el => el.Id)
  }else {
    Ids = []
  }
  let params = {
    Ids: Ids
  }
  let res = await massDispatchSend(params)
  ElMessage.success('发送任务提交成功')
  getData()

}

const handlerSendItem = async (val: any) => {
  let params = {
    Ids: [val.Id]
  }
  let res = await massDispatchSend(params)
  ElMessage.success('发送任务提交成功')
  getData()
}

const handlerPrivateLetter = (val: any) => {
  console.log(val,'1')
  privateLetterInfo.Id = val.Id
  isPrivateLetter.value = true
}

const getListName = (list: any, type: any) => {
  let info = list.find(el => el.code == type) || {}
  return info.label
}

const getData = async () => {
  let time: any = ''
  if(tabActiveName.value == '1') {
    time = [getDate('dayStartOf'),getDate('dayEndOf')]
  }else {
    time = searchForm.date
  }
  let params = {
    SourceType: tabActiveName.value == '3' ? 2 : 1,
    SendStatus: searchForm.sendStatus,
    NoticeTimeBetween: time,
    Page: searchForm.page || 1,
    PageSize: searchForm.page_size || 15
  }
  let res: any = await getMassDispatchList(params)
  state.list = res?.Data || []
  searchForm.total = res?.Total || 0
}

const onSearch = () => {
  getData()
}

const onReset = () => {
  searchForm.sendStatus = '0'
  searchForm.date = []
  getData()
}

let timer: any = null
// 开启定时器
const startTimer = () => {
  console.log('开启定时器')
  timer = setInterval(() => {
    getData()
  }, 5000)
}
// 关闭定时器
const closeTime = () => {
  console.log('关闭定时器')
  clearInterval(timer)
}
onMounted(() => {
  getData()
  // startTimer()
})

onUnmounted(() => {
  closeTime()
})
</script>
<style lang="scss" scoped>
.table-list-main {
  .tabs {

  }
  .table-search {
    margin: 16px 0;
    display: flex;
    justify-content: space-between;
  }
  .send-method-header {
    display: flex;
    align-items: center;
  }
}
// 文本溢出两行
.zw-text-ellipsis-2 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>